<template>
    <NetworkError v-if="Data.networkErrorShow" v-on:tautology="requestHandle" />
    <u-loading-page :loading="Data.loading" fontSize="14" iconSize="30" />
    <view class="active-detail-main">
        <view v-if="Data.activeMes.activityStatusName && Data.activeMes.activityStatusName.realStatus !== 3">
            <view class="head-container" :style="{ background: bgUrl }">
                <view class="head-title">
                    <view class="title">{{ Data.activeMes.activityName }}</view>
                    <view
                        >距活动{{ Data.activeMes?.activityStatusName?.realStatus === 1 ? '开始' : '结束'
                        }}<text class="num">{{ Data.curDay }}</text
                        >天<text class="num">{{ Data.curHours }}</text
                        >:<text class="num">{{ Data.curMinutes }}</text
                        >:<text class="num">{{ Data.curSeconds }}</text></view
                    >
                </view>
                <view class="head-content">
                    <view class="head-form"
                        ><view class="label">活动内容：</view
                        ><view class="text"
                            >单笔订单活动商品{{ Data.activeMes.activityType == 7 ? '金额' : '件数'
                            }}{{ getActiveMes() }}</view
                        ></view
                    >
                    <view class="head-form"
                        ><view class="label">活动时间：</view
                        ><view class="text"
                            >{{ Data.activeMes.activityStartTime }} ~ {{ Data.activeMes.activityEndTime }}</view
                        ></view
                    >
                    <view class="head-form"
                        ><view class="label">其他说明：</view
                        ><view class="text"
                            >{{ Data.activeMes?.discountSet?.discountRepeat === 1 ? '不可' : '可' }}同时使用优惠券{{
                                Data.activeMes?.discountSet?.fullReduceMail !== 1 ? '；包邮' : ''
                            }}</view
                        ></view
                    >
                </view>
            </view>
            <view class="content-list">
                <view class="title">
                    <img :src="getImgOssUrl('/ui-prod-2.5.0/active-icon.png')" class="img" />
                    <view class="name">活动商品</view>
                </view>
                <view v-if="Data.goodsList.length" class="goods-list">
                    <view>
                        <view
                            v-for="(item, index) in Data.leftData"
                            :key="index"
                            @click="goToGoodDetail(item)"
                            class="goods-item">
                            <view class="zw-empty">
                                <GoodsImgStatus v-if="item.on_sale == 3" />
                                <image :src="(item.material_src || [])[0]?.material_src" class="img" />
                            </view>

                            <view class="title"><text class="tag">满减</text>{{ item.goods_name }}</view>
                            <view class="goods-item-bottom">
                                <view class="bottom-left">
                                    <text>￥</text>
                                    <text class="price">{{ priceNum(item.goods_min_price, 0) }}</text>
                                    <text v-if="priceNum(item.goods_min_price, 1)"
                                        >.{{ priceNum(item.goods_min_price, 1) }}
                                    </text>
                                    <text class="price-qi" v-if="item.goods_min_price != item.goods_max_price">
                                        起
                                    </text>
                                </view>
                                <image
                                    :src="getImgOssUrl('/ui-prod-2.0.0/icon_img01.png')"
                                    class="bottom-right"
                                    v-if="item.on_sale != 3" />
                                <image
                                    @click.stop
                                    v-else
                                    :src="getImgOssUrl('/ui-prod-2.0.0/icon_img01_disabled.png')"
                                    class="bottom-right" />
                            </view>
                        </view>
                    </view>
                    <view>
                        <view
                            v-for="(item, index) in Data.rightData"
                            :key="index"
                            @click="goToGoodDetail(item)"
                            class="goods-item">
                            <view class="zw-empty">
                                <GoodsImgStatus v-if="item.on_sale == 3" />
                                <image :src="(item.material_src || [])[0]?.material_src" class="img" />
                            </view>
                            <view class="title"><text class="tag">满减</text>{{ item.goods_name }}</view>
                            <view class="goods-item-bottom">
                                <view class="bottom-left">
                                    <text>￥</text>
                                    <text class="price">{{ priceNum(item.goods_min_price, 0) }}</text>
                                    <text v-if="priceNum(item.goods_min_price, 1)"
                                        >.{{ priceNum(item.goods_min_price, 1) }}
                                    </text>
                                    <text class="price-qi" v-if="item.goods_min_price != item.goods_max_price">
                                        起
                                    </text>
                                </view>
                                <image
                                    :src="getImgOssUrl('/ui-prod-2.0.0/icon_img01.png')"
                                    class="bottom-right"
                                    v-if="item.on_sale != 3" />
                                <image
                                    @click.stop
                                    v-else
                                    :src="getImgOssUrl('/ui-prod-2.0.0/icon_img01_disabled.png')"
                                    class="bottom-right" />
                            </view>
                        </view>
                    </view>
                    <view class="list-loading">
                        {{ isBottom ? (listLoading ? '加载中…' : '已经到底啦！') : '' }}
                    </view>
                </view>
                <view v-else class="no-data">
                    <img class="empty" :src="getImgOssUrl('/ui-prod-2.3.0/empty-addr@2x.png')" />
                    暂无数据
                </view>
            </view>
            <view class="footer"><view class="btn" @click="toCart">去购物车</view></view>
        </view>
        <view v-if="onGoing != 1" class="active-end">
            <img class="empty" :src="getImgOssUrl('/ui-prod-2.3.0/empty-addr@2x.png')" />
            {{ onGoing == 2 ? '活动已结束' : '暂无数据' }}~
            <view @click="toHome" class="into-shop">进店逛逛</view>
        </view>
    </view>
</template>

<script setup>
import NetworkError from '@/components/networkError';
import { ref, reactive, computed, onMounted } from 'vue';
import { onShow, onHide, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import router from '@/router';
import request from '@/request';
import { floatDivide, getImgOssUrl, getDiffDateInfo, format, isObject } from '@/commons/utils';
import { getParamsBySceneHook } from '@/hooks';
import GoodsImgStatus from '@/components/goodsImgStatus';

const onGoing = ref(1); //2活动已结束 3数据返回为空
const props = defineProps({
    activityId: { type: [Number, String], default: 0 },
    scene: { type: String }
});

/** 解决推广二维码传参问题， 从props中直接取值不满足此情况，故引入下面参数 */
let activityIdArg = ref(0);

const bgUrl = ref(`url(${getImgOssUrl('/ui-prod-2.5.0/reduce-bg.png')})`);
let listLoading = ref(false);
const Data = reactive({
    timer: null,
    loading: true,
    networkErrorShow: true,
    curDay: 0,
    curHours: '00',
    curMinutes: '00',
    curSeconds: '00',
    page: 1,
    perPage: 10,
    scrollTop: 0,
    totalCount: 0,
    activeMes: {},
    goodsList: [],
    leftData: [],
    rightData: []
});
const priceNum = (amount, index) => {
    let price = floatDivide(amount, 100);
    let list = [];
    try {
        list = price.toString().split('.');
    } catch (e) {
        list = [Number(price)];
    }
    return list[index];
};
const handleCountDown = timeData => {
    const timeInfo = getDiffDateInfo(format(new Date()), format(timeData));
    const { curDay, curHours, curMinutes, curSeconds, millisecondDiff } = timeInfo;
    Data.curDay = curDay;
    Data.curHours = curHours;
    Data.curMinutes = curMinutes;
    Data.curSeconds = curSeconds;
    if (millisecondDiff <= 0) {
        clearInterval(Data.timer);
    }
};
const getActiveMes = () => {
    const { activityType } = Data.activeMes;
    if (Object.keys(Data.activeMes).length) {
        const { orderAmount, reduce } = Data.activeMes.discountSet;
        if (activityType === 7) {
            return `满${orderAmount / 100}元减${reduce / 100}元`;
        } else {
            return `满${orderAmount}件打${reduce / 10}折`;
        }
    }
};

const isBottom = computed(() => {
    return Data.scrollTop > 50;
});
onPageScroll(e => {
    Data.scrollTop = e.scrollTop;
});
const goToGoodDetail = item => {
    router.push({
        path: '/pages-cart/good/index',
        query: {
            goodsId: item.id
        }
    });
};

const getSceneParams = async () => {
    const res = await getParamsBySceneHook(props.scene);
    activityIdArg.value = res.activityId;
};

const requestHandle = async () => {
    if (!Data.leftData.length) {
        Data.leftData = [];
        Data.rightData = [];
        Data.page = 1;
        if (props.scene) {
            await getSceneParams();
        }
        await getGoodsList();
    }

    if (!Data.timer && Object.keys(Data.activeMes).length) {
        Data.timer = setInterval(() => {
            const { activityStartTime, activityEndTime } = Data.activeMes;
            const { realStatus } = Data.activeMes.activityStatusName;
            handleCountDown(realStatus === 1 ? activityStartTime : activityEndTime);
        }, 1000);
    }
};
onShow(requestHandle);

const getGoodsList = async () => {
    listLoading.value = true;
    const { page, perPage } = Data;
    const { activityId } = props;
    if (Data.networkErrorShow) Data.loading = true;
    try {
        let res = await request('fullReduceDetail', {
            page,
            perPage,
            id: activityIdArg.value || activityId
        });
        Data.networkErrorShow = false;
        Data.loading = false;
        Data.activeMes = res.data;

        if (!Data.timer && Object.keys(Data.activeMes).length) {
            Data.timer = setInterval(() => {
                const { activityStartTime, activityEndTime } = Data.activeMes;
                const { realStatus } = Data.activeMes.activityStatusName;
                handleCountDown(realStatus === 1 ? activityStartTime : activityEndTime);
            }, 1000);
        }
        let list = Data.activeMes?.data?.list || [];

        if (page === 1) {
            Data.goodsList = list;
        } else {
            Data.goodsList = Data.goodsList.concat(list);
        }
        list.forEach((item, index) => {
            if ((index + 1) % 2) {
                Data.leftData = [...Data.leftData, item];
            } else {
                Data.rightData = [...Data.rightData, item];
            }
        });
        listLoading.value = false;
        Data.totalCount = Data.activeMes?.data?.totalCount;
        onGoing.value = Object.keys(Data.activeMes).length
            ? Data.activeMes?.activityStatusName && Data.activeMes?.activityStatusName?.realStatus !== 3
                ? 1
                : 2
            : 3;
    } catch (error) {
        Data.loading = false;
        if (isObject(error)) {
            uni.showToast({
                title: error.data.msg,
                icon: 'none',
                duration: 3000
            });
        }
    }
};
onHide(() => {
    clearInterval(Data.timer);
    Data.timer = null;
});
// 上拉加载
onReachBottom(() => {
    if (Data.totalCount === Data.goodsList.length) {
        return;
    }
    Data.page++;
    getGoodsList();
});
const toCart = () => {
    router.switchTab({ url: '/pages/tabbar/cart' });
};
// 进店逛逛
const toHome = () => {
    router.switchTab({ url: '/pages/tabbar/home' });
};
</script>

<style lang="scss" scoped src="./index.scss"></style>
